import os.path
from datetime import datetime
from PIL import Image
from bs4 import BeautifulSoup

from src.init.init_db import db
from src.init.init_path import PATH, BASE_PATH
from src.model.AritcleModel import ArticleModel
from src.model.PictureModel import PictureModel

ALLOWED_EXTENSIONS = {"jpeg", "png", "webp", "gif", "jpg", "bmp"}

class PictureTool:

    def __init__(self):
        self.aid = 0

    def init(self, aid:int, file:Image):
        if ArticleModel.query.filter_by(aid=aid).first() is None:
            return {"pid":0, "err":"文章不存在！"}
        if file is None:
            return {"pid":0, "err":"未传图片！"}
        filetype = file.filename.split('.')[-1]
        if filetype not in ALLOWED_EXTENSIONS:
            return {"pid":0, "err":"图片格式不符或图片为空！"}
        #将文件名转换为当前时间
        nowtime = datetime.now()
        fname = nowtime.strftime('%Y-%m-%d-%H%M%S')+ f"{nowtime.microsecond // 1000:03d}" + "." + filetype
        url = os.path.join(BASE_PATH, "img", fname)
        purl = "imgresource" + PATH + "/" + fname
        file.save(url)
        picture = PictureModel(aid=aid, purl=purl)
        db.session.add(picture)
        db.session.commit()
        return {"aid": picture.aid, "purl": picture.purl, "pid": picture.pid}


    def delete_not_exit(self, aid:int, content:str):
        if ArticleModel.query.filter_by(aid=aid).first() is None:
            return {"success":False, "err":"文章不存在！"}
        if content is None:
            return {"success":False, "err":"未获取到文章内容！"}
        # 获取文章内容中的所有图片标签
        soup = BeautifulSoup(content, "html.parser")
        img_tags = soup.find_all("img")
        img_srcs = []
        for tag in img_tags:
            img_srcs.append(tag.get("src").split("://")[1].split("/", 1)[1])
        # 在数据库中找到该文章的所有图片
        imglist = PictureModel.query.filter_by(aid=aid).all()
        # 在数据库中去除文章中已经删除的图片
        for img in imglist:
            if img.purl not in img_srcs:
                url = os.path.join(BASE_PATH, img.purl.split("/", 1)[1])
                os.remove(url)
                picture = PictureModel.query.filter_by(aid=aid, purl=img.purl).first()
                db.session.delete(picture)
                db.session.commit()
        return {"success":True}


    def delete_picture(self, aid:int):
        pictures = PictureModel.query.filter_by(aid=aid).all()
        for picture in pictures:
            purl = picture.purl
            url = os.path.join(BASE_PATH, purl.split("/", 1)[1])
            os.remove(url)
            db.session.delete(picture)
            db.session.commit()